package com.suse.service.view.edu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.suse.service.view.edu.model.entity.Chapter;
import com.suse.service.view.edu.mapper.ChapterMapper;
import com.suse.service.view.edu.model.entity.Video;
import com.suse.service.view.edu.model.vo.ChapterVo;
import com.suse.service.view.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suse.service.view.edu.service.VideoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-16
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Resource
    private VideoService videoService;

    @Override
    public List<ChapterVo> getChapterList(String courseId) {
        // 查询课程下的所有章节列表
        List<Chapter> chapterList = lambdaQuery()
                .select(Chapter::getId,
                        Chapter::getTitle)
                .eq(Chapter::getCourseId,courseId)
                .list();
        // 查询课程下的所有视频列表
        List<Video> videoList = videoService.lambdaQuery()
                .select(Video::getId,
                        Video::getTitle,
                        Video::getVideoSourceId,
                        Video::getIsFree,
                        Video::getChapterId)
                .eq(Video::getCourseId,courseId)
                .list();
        // 建立章节ID与视频视图对象的映射关系
        // 降低时间复杂度
        Map<String, List<Video>> map = new HashMap<>();
        for (Video video : videoList) {
            String chapterId = video.getChapterId();
            if (map.containsKey(chapterId)) {
                List<Video> chapterVideoList = map.get(chapterId);
                chapterVideoList.add(video);
            }else {
                List<Video> chapterVideoList = new ArrayList<>();
                chapterVideoList.add(video);
                map.put(chapterId,chapterVideoList);
            }
        }
        List<ChapterVo> chapterVoList = new ArrayList<>();
        for (Chapter chapter : chapterList) {
            List<Video> chapterVideoList = map.get(chapter.getId());
            ChapterVo chapterVo = BeanUtil.copyProperties(chapter, ChapterVo.class);
            chapterVo.setVideoList(chapterVideoList);
            chapterVoList.add(chapterVo);
        }
        return chapterVoList;
    }
}
